<template>
  <div>
    <select-picker-modal ref="selectPickerModal" @value="getPicker" :type="1"></select-picker-modal>
    <el-col :span="24">
      <OrderInfo :chOrderService="chOrderService" :id="id" :routeName="routeName" :state="state"></OrderInfo>
    </el-col>
    <!--客户信息：服务订单有-->
    <el-col :span="24">
      <UserInfo :chOrderConsigneeInfo="chOrderConsigneeInfo" v-if="chOrderService.orderType === 'STORAGEORDERTYPE01'"></UserInfo>
    </el-col>
    <el-col :span="24">
      <Portlet title="商品信息"  style="position:relative;">
        <div slot="tools" v-if="!chOrderService.doScan">
          <el-button type="primary" @click.prevent="showSelectPickerModal">指派拣货员</el-button>
          <el-button type="primary" :loading="loading" @click.prevent="submit">提交分配结果</el-button>
        </div>
        <el-form ref="searchForm" class="el-form-col" label-width="80px" :model="search" label-position="left">
          <el-row>
            <el-col :lg="5" :xl="5">
              <el-form-item prop="manufacturersName" label="厂家名称">
                <el-input clearable placeholder="" v-model="search.manufacturersName"></el-input>
              </el-form-item>
            </el-col>
            <el-col :lg="5" :xl="5">
              <el-form-item prop="productName" label="所属产品">
                <el-input clearable placeholder="" v-model="search.productName"></el-input>
              </el-form-item>
            </el-col>
            <el-col :lg="5" :xl="5">
              <el-form-item prop="packageName" label="包件名称">
                <el-input clearable placeholder="" v-model="search.packageName"></el-input>
              </el-form-item>
            </el-col>
            <el-col :lg="5" :xl="5">
              <el-form-item >
                <el-button type="primary" @click.prevent="reset">重置</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <el-form :model="model" :rules="rules" label-position="left" ref="elForm" label-width="100px">
        <el-form-item label-width="0" prop="chSortingPackageBeans" :rules="[
                {required: true, message: '货物信息必须', trigger: 'change', type: 'array'}
             ]">
          <el-table
            ref="table"
            border
            max-height="500"
            :data="model.chSortingPackageBeans | filterActive(this.search)"
            class="text-center"
            @selection-change="handleSelectionChange"
          >
            <el-table-column
              type="selection"
              width="55">
            </el-table-column>
            <el-table-column
              prop="manufacturersName"
              label="厂家名称"
            >
            </el-table-column>
            <el-table-column
              align="center"
              min-width="120px"
              prop="productNo"
              label="商品编号">
            </el-table-column>
            <el-table-column
              align="center"
              min-width="120px"
              prop="productName"
              label="商品名称">
            </el-table-column>
            <el-table-column
              align="center"
              min-width="120px"
              prop="bigClass"
              label="商品大类">
            </el-table-column>
            <el-table-column
              align="center"
              min-width="120px"
              prop="middleClass"
              label="商品小类">
            </el-table-column>
            <el-table-column
              align="center"
              min-width="120px"
              prop="productNum"
              label="商品数量">
            </el-table-column>
            <el-table-column
              align="center"
              min-width="120px"
              prop="packageNum"
              label="包件数量">
            </el-table-column>
            <el-table-column
              v-if="productType == 1"
              align="center"
              min-width="80px"
              prop="standard"
              label="规格">
            </el-table-column>
            <el-table-column
              v-if="productType == 1"
              align="center"
              min-width="120px"
              prop="packageCode"
              label="包件编号">
            </el-table-column>
            <el-table-column
              v-if="productType == 1"
              min-width="150px"
              prop="packageName"
              align="center"
              label="包件名称">
            </el-table-column>

            <el-table-column
              v-if="productType == 1"
              align="center"
              min-width="100px"
              prop="packageOneVolume"
              label="单包件体积">
            </el-table-column>
            <el-table-column
              v-if="productType == 1"
              align="center"
              min-width="100px"
              prop="packageOneWeight"
              label="单包件重量">
            </el-table-column>
            <el-table-column
              v-if="productType == 1"
              prop="unit"
              label="包件单位">
            </el-table-column>
            <el-table-column
              prop="positionId"
              width="120"
              label="分配库位">
              <template slot-scope="scope">
                <div v-if="!chOrderService.doScan">
                  <el-form-item label-width="0" :prop="'chSortingPackageBeans.' + scope.$index + '.positionId'" :rules="[
                        {required: true, message: '库位必须', trigger: 'change'}
                      ]">
                    <select-position :id="chOrderService.orderId" v-model="scope.row.positionId"></select-position>
                  </el-form-item>
                </div>
                <div v-else>
                  {{ scope.row.positionName }}
                </div>
              </template>
            </el-table-column>
            <el-table-column
              prop="sortingPersonName"
              label="拣货员">
            </el-table-column>
          </el-table>
        </el-form-item>
        </el-form>
        <div style="position:absolute;left:140px;top:17px;font-size:14px;color:red">商品类型： {{getProductName(productType)}}</div>
        <div v-if="state == 3" style="position:absolute;right:26px;top:8px;font-size:14px;"><el-button type="primary" @click.prevent="submit">确认入库</el-button></div>
        <!--总的包件体积重量-->
        <el-row style="margin-top:15px;font-size:14px">
          <el-col :span="6">
            总包件：<span> {{chOrderService.totalPackage}} 件</span>
          </el-col>
          <el-col :span="6">
            总体积：<span> {{chOrderService.totalVolume}} m³</span>
          </el-col>
          <el-col :span="6">
            总重量：
            <span v-if="chOrderService.totalWeight"> {{chOrderService.totalWeight}} kg</span>
            <span v-else>/</span>
          </el-col>
        </el-row>
      </Portlet>
    </el-col>
  </div>
</template>

<script>
import {dotData, alert} from '@/utils'
import OrderInfo from '@/views/oms/enterWarehouse/warehousingOrder/OrderInfo'
import UserInfo from '@/views/oms/enterWarehouse/warehousingOrder/UserInfo'
import CustomerInfo from '@/views/oms/enterWarehouse/warehouseConfirm/CustomerInfo'
import SelectPosition from '@/views/oms/business/SelectPositionByEnter'
import SelectPickerModal from '@/views/oms/business/SelectPickerModal'
import {decimalNumFilter, unixTimestampFilter} from '@/filters'
import DBLike from '@/utils/DBLike'
export default {
  name: 'warehouseAllocationShow',
  components: {
    UserInfo,
    OrderInfo,
    CustomerInfo,
    DBLike,
    SelectPosition,
    SelectPickerModal
  },
  filters: {
    decimalNumFilter,
    unixTimestampFilter,
    filterActive: (arr, search) => {
      return new DBLike(arr).search(search)
    }
  },
  data() {
    return {
      id: this.$route.params.id,
      state: this.$route.query.state,
      routeName: this.$route.name,
      headerDetail: {},
      chOrderService: {}, // 订单信息
      chOrderConsigneeInfo: {}, // 客户信息
      productDetailBeans: [], // 产品信息
      loading: false,
      model: {
        chSortingPackageBeans: [],
        warehouseId: '',
        cargoOwnerId: ''
      },
      params: {
        id: this.$route.params.orderId
      },
      packageIdArr: [],
      rules: {},
      // cargoOwnerArr: [], // 模拟 库位下拉选项
      search: {
        manufacturersName: '',
        productName: '',
        packageName: ''
      }
      // totalItem: 0
    }
  },
  created() {
    // 获取表头
    if (this.id) {
      this.getDetail()
    }
  },
  computed: {
    // 标准产品1，通用产品2==自定义产品3
    productType() {
      return dotData(this.chOrderService, 'productType') || 1 // 默认为标准产品
    },
    // 总包件：num累加
    totalPackage() {
      let num = 0
      if (Array.isArray(this.model.chSortingPackageBeans)) {
        this.model.chSortingPackageBeans.forEach(v => {
          num += v.num
        })
      }
      return decimalNumFilter(num)
    },
    // 总体积：单包件*num
    totalVolumes() {
      let num = 0
      if (Array.isArray(this.model.chSortingPackageBeans)) {
        this.model.chSortingPackageBeans.forEach(v => {
          num += (v.packageOneVolume * v.num)
        })
      }
      return decimalNumFilter(num)
    },
    // 总重量：单重量*num
    totalWeight() {
      let num = 0
      if (Array.isArray(this.model.chSortingPackageBeans)) {
        this.model.chSortingPackageBeans.forEach(v => {
          num += v.packageOneWeight * v.num
        })
      }
      return decimalNumFilter(num)
    }
  },
  methods: {
    unixTimestampFilter,
    searchFunc() {
      // this.params = merge(this.params, this.search)
      // this.httpGetPackage()
    },
    // reset 重置搜索框
    reset(searchForm) {
      this.$refs.searchForm.resetFields()
    },
    // 获取详情
    getDetail() {
      this.$ajax.get('/ms-warehouse-order/recordOrder/orderDetailBean', {id: this.id}).then(response => {
        if (response.success) {
          this.totalItem = response.total
          this.chOrderService = response.data.chOrderService || {} // 订单信息
          this.chOrderConsigneeInfo = response.data.chOrderConsigneeInfo || {} // 客户信息
          // 获取包件 并初始化 表单model
          this.model.chSortingPackageBeans = response.data.productDetailBeans || [] // 商品信息
          this.$nextTick(function() {
            // 未分配
            if (this.chOrderService.orderState === 'INPUTWAREHOUSE-100') {
              setTimeout(_ => {
                this.checked()
                this.getPickup()
              }, 500)
            }
          })
        }
      })
    },
    // 默认全选
    checked() {
      for (let i = 0; i < this.model.chSortingPackageBeans.length; i++) {
        this.$refs.table.toggleRowSelection(this.model.chSortingPackageBeans[i], true)
      }
    },
    // 过滤 商品类型 最终：productType通过计算而来：标准产品1，通用产品2==自定义产品3
    getProductName(type) {
      if (type === 1) {
        return '标准产品'
      } else if (type === 2) {
        return '通用产品'
      } else if (type === 3) {
        return '自定义产品'
      }
      return ''
    },
    // 列表选择
    handleSelectionChange(val) {
      this.packageIdArr = []
      val.forEach(v => {
        this.packageIdArr.push(v.packageId)
      })
    },
    // 显示指派拣货员modal
    showSelectPickerModal() {
      if (this.packageIdArr.length) {
        this.isVisible = true
        this.$refs.selectPickerModal.show()
      } else {
        alert('请选择需要指派的包件！')
      }
    },
    // 获取拣货人
    getPickup() {
      this.$ajax.get('/ms-warehouse-order/inPutWarehouse/getSorterList').then(response => {
        if (!response.data) {
          alert('获取拣货员失败！')
          return
        }
        this.packageIdArr.forEach(v => {
          this.model.chSortingPackageBeans.find((x) => {
            if (x.packageId === v) {
              x.sortingPersonId = response.data[0].id
              x.sortingPersonName = response.data[0].name
            }
          })
        })
      })
    },
    // 获取拣货员
    getPicker(val) {
      this.picker = val
      if (!this.packageIdArr.length) {
        alert('未获取需指派的包件！')
        return
      }
      if (!this.picker) {
        alert('未获取拣货员')
        return
      }
      this.savePackagePicker()
    },
    // 保存包件拣货员
    savePackagePicker() {
      this.packageIdArr.forEach(v => {
        let that = this
        this.model.chSortingPackageBeans.find((x) => {
          if (x.packageId === v) {
            x.sortingPersonId = that.picker.id
            x.sortingPersonName = that.picker.name
          }
        })
      })
    },
    submit() {
      this.$refs.elForm.validate(result => {
        if (!result) {
          this.$alert('请确认入库单中每个包件均分配了库位及拣货员，需完善后再次提交！', '信息未完善', {
            confirmButtonText: '确定',
            center: true
          })
          return
        }
        // 取值
        let data = {
          id: this.id
        }
        this.loading = true
        let chSortingPackageBeans = []
        if (Array.isArray(this.model.chSortingPackageBeans)) {
          let arr = this.model.chSortingPackageBeans
          for (let i in arr) {
            if (arr[i].packageId && arr[i].positionId && arr[i].sortingPersonId) {
              chSortingPackageBeans.push({
                packageId: arr[i].packageId,
                positonId: arr[i].positionId,
                sortingPersonId: arr[i].sortingPersonId
              })
            } else {
              this.$alert('请确认入库单中每个包件均分配了库位及拣货员，需完善后再次提交！', '信息未完善', {
                confirmButtonText: '确定',
                center: true
              })
              this.loading = false
              return false
            }
          }
        }
        data.chSortingPackageBeans = chSortingPackageBeans
        // 提交
        this.$confirm('<p>确定提交入库计划？</p><p>（提交后将按计划生拣货单）</p>', '提示', {
          confirmButtonText: '提交',
          cancelButtonText: '取消',
          type: 'warning',
          dangerouslyUseHTMLString: true,
          center: true,
          beforeClose: (action, instance, done) => {
            if (action === 'confirm') {
              instance.confirmButtonLoading = true
              instance.confirmButtonText = '提交中...'
              this.$ajax.post('/ms-warehouse-order/recordOrder/insertSorting', data).then(response => {
                const success = dotData(response, 'success')
                if (success) {
                  done()
                  instance.confirmButtonLoading = false
                  this.loading = false
                  setTimeout(() => {
                    this.$confirm('提交成功', '提示', {
                      type: 'success',
                      center: true,
                      confirmButtonText: '确定',
                      showCancelButton: false,
                      closeOnClickModal: false
                    }).then(_ => {
                      this.$router.push({path: '/ss-oms/enterWarehouse/warehouse-allocation/index'})
                    })
                  }, 1000)
                } else {
                  done()
                  instance.confirmButtonLoading = false
                  setTimeout(() => {
                    this.loading = false
                  }, 500)
                }
              })
            } else {
              done()
              this.loading = false
            }
          }
        })
      })
    }
  }
}
</script>
